package com.lib.image.until

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.provider.MediaStore
import com.lib.image.BuildConfig
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

object FileUtil {

    fun createTempVideoFile(ctx: Context, fileName: String): File {
        return createFile(ctx, fileName, 4)
    }

    fun createTempImageFile(ctx: Context, fileName: String): File {
        return createFile(ctx, fileName, 3)
    }

    fun createVideoFile(ctx: Context, fileName: String): File {
        return createFile(ctx, fileName, 2)
    }

    fun createImageFile(ctx: Context, fileName: String): File {
        return createFile(ctx, fileName, 1)
    }

    fun getImageFolderFile(ctx: Context): File {
        return getFolderFile(ctx, 1)
    }

    fun getVideoFolderFile(ctx: Context): File {
        return getFolderFile(ctx, 2)
    }

    fun getTempImageFolderFile(ctx: Context): File {
        return getFolderFile(ctx, 3)
    }

    fun getTempVideoFolderFile(ctx: Context): File {
        return getFolderFile(ctx, 4)
    }

    private fun getFolderFile(ctx: Context, type: Int): File {
        val folder = getFolder(type)
        return ctx.getExternalFilesDir(folder)!!
    }

    private fun createFile(ctx: Context, fileName: String, type: Int): File {
        val fileFolder = getFolderFile(ctx, type)
        val filePath = "${fileFolder.absolutePath}${File.separator}${fileName}"
        val file = File(filePath)
        if (!file.exists()) {
            file.createNewFile()
        }
        return file
    }

    private fun getFolder(type: Int): String {
        return when (type) {
            1 -> BuildConfig.FOLDER_IMAGE
            2 -> BuildConfig.FOLDER_VIDEO
            3 -> BuildConfig.FOLDER_TEMP_IMAGE
            4 -> BuildConfig.FOLDER_TEMP_VIDEO
            else -> BuildConfig.FOLDER_IMAGE
        }
    }

    @Throws(Exception::class)
    fun saveBitmap(
        context: Context,
        bitmap: Bitmap,
        file: File,
        quality: Int
    ) {
        var outputStream: FileOutputStream? = null
        try {
            outputStream = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
            if (!file.exists()) {
                return
            }
            val values = ContentValues()
            values.put(MediaStore.Images.Media.DATA, file.absolutePath)
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            val uri = context.contentResolver
                .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
            //会导致相册创建两张图片
            //https://blog.csdn.net/weixin_38327562/article/details/78031989
//                MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                        file.getAbsolutePath(), file.getName(), null);
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
        } catch (e: FileNotFoundException) {
            throw e
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    /**
     * android 11+
     */
    private fun pushAlbum11(context: Context) {
        val resolver = context.contentResolver

        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, "clip_${System.currentTimeMillis()}")
            put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
        }
        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        if (uri != null) {
            resolver.openOutputStream(uri).use {
//                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
            }
        }
    }
}

object FileCacheManager {

    fun clearImageDisk(ctx: Context): Boolean {
        val file = FileUtil.getImageFolderFile(ctx)
        if (file.exists()) {
            val ok = ShellUtils.execCommand("rm -rf ${file.absolutePath}", false).result == 0
            if(ok) {
                updateFileFromDatabase(ctx, file.absolutePath)
            }
            return ok
        }
        return true
    }

    fun clearVideoDisk(ctx: Context): Boolean {
        val file = FileUtil.getVideoFolderFile(ctx)
        if (file.exists()) {
            val ok = ShellUtils.execCommand("rm -rf ${file.absolutePath}", false).result == 0
            if(ok) {
                updateFileFromDatabase(ctx, file.absolutePath)
            }
            return ok
        }
        return true
    }

    /**
     * 这是删除整个文件夹
     * 删除文件后更新数据库  通知媒体库更新文件夹,！！！！！filepath（文件夹路径）要求尽量精确，以防删错
     * android 11无效
     * @param context
     * @param filepath
     * @return
     */
    fun updateFileFromDatabase(
        context: Context,
        filepath: String
    ): Boolean {
        val where = MediaStore.Audio.Media.DATA + " like \"" + filepath + "%" + "\""
        var opCount = 0
        opCount = try {
            context.contentResolver
                .delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, where, null)
        }catch (e: Exception) {
            0
        }
        return opCount > 0
    }
}